var app = getApp(),
  fetchApi = require("../../../utils/httpPost.js"),
  formatTime = require("../../../component/common.js")
import Toast from '../../../component/vant/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    date: {
      maxRange: [],
      selectSingle: null,
      selectRange: [],
      selectMultiple: [],
      quickSelect1: null,
      quickSelect2: [],
      customColor: [],
      customConfirm: [],
      customRange: null,
      customDayText: [],
      customPosition: null,
    },
    couponData: [],
    nick_name: '',
    qrcode_id: 0,
    use_type: -1,
    isLoading: true,
    qrtype: '',
    band_user_id: 0,
    estate_id: 0,
    estate_name: '',
    radioSize: '1',
    radioCheck: '1',
    commentContent: '',
    check_state: 1,
    dicts: [],
    submitState: false,
    singlePrice: 0,

    type: 'single',
    round: true,
    color: undefined,
    minDate: new Date(2012, 0, 10).getTime(),
    maxDate: new Date(
      new Date().getFullYear(),
      new Date().getMonth() + 6,
      new Date().getDate()
    ).getTime(),
    maxRange: undefined,
    position: undefined,
    formatter: undefined,
    showConfirm: false,
    showCalendar: false,
    tiledMinDate: new Date(2012, 0, 10).getTime(),
    tiledMaxDate: new Date(2012, 2, 20).getTime(),
    confirmText: undefined,
    confirmDisabledText: undefined,
    firstDayOfWeek: 0,
    room_no: '',
    room_areas: '',
    phone_num: '',
    payMoney: 0.00,
    totalMoney: 0.00,
    diKouMoney: 0.00,
    diKouRate: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options', options)
    if (options.qrtype) {
      this.setData({
        qrtype: options.qrtype
      })
      if (options.id) {
        this.data.estate_id = parseInt(options.id);
      }
    }
    this.onHttpInit()
  },
  onHttpInit: function () {
    var that = this;
    fetchApi.httpPost('/estate/detail', {
      estate_id: that.data.estate_id,
    }, function (res) {
      console.log("获取二维码数据", res)
      console.log('res', res)
      if (res.data.code == 0) {
        that.data.diKouRate = res.data.data.diKouRate;
        that.setData({
          singlePrice: res.data.data.estate.singlePrice,
          estate_name: res.data.data.estate.estateName,
        })
      } else {
        Toast.fail(res.data.msg)
      }
      that.setData({
        netWork: true,
        isLoading: false,
      })
    }, function () {
      that.setData({
        netWork: false,
        hasData: false,
        isLoading: false,
      })
    })
  },
  trim: function (t) {
    return t.replace(/(^\s*)|(\s*$)/g, "");
  },
  getPrice() {
    var payPrice = 0;
    var singlePrice = this.data.singlePrice;
    var totalPrice = 0;
    var diKouPrice = 0;
    if (this.data.room_areas != '') {
      var areas = parseInt(this.data.room_areas);
      payPrice = areas * singlePrice;
      totalPrice = payPrice;
      console.log('payPrice', payPrice);
      console.log('totalPrice', totalPrice)
    }
    this.setData({
      totalMoney: totalPrice,
      diKouMoney: diKouPrice,
      payMoney: payPrice,
    })
  },

  roomNoInput(e) {
    this.data.room_no = e.detail;
  },
  phoneNumInput(e) {
    this.data.phone_num = e.detail;
  },
  roomAreaInput(e) {
    console.log('roomAreaInput', e);
    this.data.room_areas = e.detail;
    console.log('this.data.room_areas', this.data.room_areas)
    this.getPrice()
  },
  submitOrder: function (e) {
    var that = this

    console.log('selectRange', this.data.date.selectRange);
    console.log('customDayText', this.data.date.customDayText);
    console.log('customRange', this.data.date.customRange);

    if (that.data.room_no == '' || that.data.room_no == undefined || that.data.room_no == 0) {
      Toast.fail("请输入房间号码");
      return;
    }

    if (this.data.date.selectRange.length == 0) {
      Toast.fail("请选择时间区间");
      return;
    } else {
      var begin_date = formatTime.formatTimeTwo(this.data.date.selectRange[0], 'Y-M-D')
      console.log('begin_date', begin_date)
      this.data.begin_date = begin_date;
      var end_date = formatTime.formatTimeTwo(this.data.date.selectRange[1], 'Y-M-D')
      console.log('end_date', end_date)
      this.data.end_date = end_date;
    }

    if (that.data.room_areas == '' || that.data.room_areas == undefined || that.data.room_areas == 0) {
      Toast.fail("请输入房屋面积");
      return;
    }

    if (that.data.phone_num == '' || that.data.phone_num == undefined || that.data.phone_num == 0) {
      Toast.fail("请输入业主手机号");
      return;
    }

    that.setData({
      submitting: true
    })

    fetchApi.httpPost('/property/addOrder', {
      estate_id: that.data.estate_id,
      room_no: that.data.room_no,
      room_areas: that.data.room_areas,
      use_integral: that.data.use_integral,
      begin_date: that.data.begin_date,
      end_date: that.data.end_date,
      phone_num: that.data.phone_num,
    }, function (res) {
      console.log('res', res)
      if (res.data.code == 0) {
        var order_id = res.data.data;
        that.requestPay(order_id)
        console.log('order_id', order_id)
      } else {
        Toast.fail(res.data.msg);
      }
    }, function () {})
  },
  requestPay: function (order_id) {
    var that = this
    fetchApi.httpPost('/pay/requestPayProperty', {
      order_id: order_id,
      subject: '交物业费'
    }, function (res) {
      console.log('提交订单', res)
      if (res.data.code == 0) {
        var pay_data = res.data.data;
        var wxpayinfo = JSON.parse(res.data.data)
        console.log('pay_data', pay_data)
        if (wxpayinfo.result_code == 'SUCCESS') {
          wx.requestPayment({
            timeStamp: wxpayinfo.timeStamp,
            nonceStr: wxpayinfo.nonceStr,
            package: wxpayinfo.package,
            signType: wxpayinfo.signType,
            paySign: wxpayinfo.paySign,
            success(res) {
              console.log('requestPayment success', res)
              wx.redirectTo({
                url: '/pages/pay/payResult/index?type=wyfee&order_id=' + order_id,
              })
            },
            fail(res) {
              console.log('requestPayment fail', res)
            }
          })
        } else if (wxpayinfo.result_code == 'NOT_NEED_PAY') { //不跳转支付
          wx.redirectTo({
            url: '/pages/pay/payResult/index?type=wyfee&order_id=' + order_id,
          })
        }

      } else {
        that.setData({
          isLoading: false,
          loading: true,
          netWork: true
        })
      }
    }, function () {
      that.setData({
        isLoading: false,
        loading: true,
        netWork: true,
      })
    })
  },
  bindInput: function (t) {
    console.log("情况说明输入", t)
    this.data.commentContent = t.detail || "";
  },
  onConfirm(event) {
    console.log('onConfirm', event);
    this.setData({
      showCalendar: false
    });

    this.setData({
      [`date.${this.data.id}`]: Array.isArray(event.detail) ?
        event.detail.map((date) => date.valueOf()) :
        event.detail.valueOf(),
    });
  },

  onSelect(event) {
    console.log(event);
  },

  onUnselect(event) {
    console.log(event);
  },

  onClose() {
    this.setData({
      showCalendar: false
    });
  },

  onOpen() {
    console.log('open');
  },

  onOpened() {
    console.log('opened');
  },

  onClosed() {
    console.log('closed');
  },

  resetSettings() {
    this.setData({
      round: true,
      color: null,
      minDate: new Date(2012, 0, 10).getTime(),
      maxDate: new Date(
        new Date().getFullYear(),
        new Date().getMonth() + 6,
        new Date().getDate()
      ).getTime(),
      maxRange: null,
      position: 'bottom',
      formatter: null,
      showConfirm: true,
      confirmText: '确定',
      confirmDisabledText: null,
    });
  },

  show(event) {
    this.resetSettings();
    const {
      type,
      id
    } = event.currentTarget.dataset;
    const data = {
      id,
      type,
      showCalendar: true,
    };

    switch (id) {
      case 'quickSelect1':
      case 'quickSelect2':
        data.showConfirm = false;
        break;
      case 'customColor':
        data.color = '#07c160';
        break;
      case 'customConfirm':
        data.confirmText = '完成';
        data.confirmDisabledText = '请选择结束时间';
        break;
      case 'customRange':
        data.minDate = new Date(2010, 0, 1).getTime();
        data.maxDate = new Date(2010, 0, 31).getTime();
        break;
      case 'customDayText':
        data.minDate = new Date(2010, 4, 1).getTime();
        data.maxDate = new Date(2010, 4, 31).getTime();
        data.formatter = this.dayFormatter;
        break;
      case 'customPosition':
        data.round = false;
        data.position = 'right';
        break;
      case 'maxRange':
        data.maxRange = 3;
        break;
    }
    this.setData(data);
  },

  dayFormatter(day) {
    const month = day.date.getMonth() + 1;
    const date = day.date.getDate();

    if (month === 5) {
      if (date === 1) {
        day.topInfo = '劳动节';
      } else if (date === 4) {
        day.topInfo = '五四青年节';
      } else if (date === 11) {
        day.text = '今天';
      }
    }

    if (day.type === 'start') {
      day.bottomInfo = '入店';
    } else if (day.type === 'end') {
      day.bottomInfo = '离店';
    }
    return day;
  },

})